#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : bigDataProject 
@File    : order_pay_server.py
@IDE     : PyCharm 
@Author  : Mario
@Date    : 2022/11/15 09:56 
@Describe: POS订单支付业务实现
"""
from typing import Text, List, Union

from api.pos_api.pay.pay_api import PayAPI
from api.pos_api.table.table_api import TableAPI
from api.pos_api.user.user_api import UserAPI
from fast_api.model.dto.baseResponseDto import BaseResponseDto
from fast_api.model.enum.pay.order_pay_way_enum import ORDER_PAY_WAY_ENUM
from model.exceptions import RequestFailedException
from utils.common.common_control import get_json_result


class OrderPayServer:
    def __init__(self, brand_code: Text, env: Text) -> None:
        self.pay_api = PayAPI(brand_code, env)
        self.table_api = TableAPI(brand_code, env)
        self.user_api = UserAPI(brand_code, env)

    def pay_mode_cancel(self, order_no: Text, pay_no: Text) -> None:
        """
        取消支付方式
        :param order_no: 订单号
        :param pay_no: 支付号(商户订单号)
        """
        self.pay_api.pay_xinmeida_cancel(order_no, pay_no)

    def check_order_pay_mode(self, order_pay_list: List) -> None:
        """
        检查订单中的所有支付方式并且把支付中和支付失败的方式取消
        :param order_pay_list: 支付信息
        """
        for pay_info in order_pay_list:
            # 支付结果: 0-支付中, 1支付成功, 2支付失败
            if pay_info['status'] != '1':
                pay_code = pay_info['payCode']
                if pay_code == ORDER_PAY_WAY_ENUM.XIN_MEI_DA.value[0]:
                    order = pay_info['orderNo']
                    pay_no = pay_info['payNo']
                    self.pay_mode_cancel(order, pay_no)

    def order_need_pay_amount(self, order_no: Text) -> Union[int, float]:
        """
        获取订单待付金额
        :param order_no: 订单详情
        :return: 待付金额
        """
        order_detail = self.pay_api.order_pay_detail(order_no)
        need_pay_amount = get_json_result(order_detail, '$..needPayAmount')
        return need_pay_amount

    def order_pay_amount_handle(self, order_no: Text) -> Union[int, float]:
        """
        订单金额处理
        :param order_no: 订单号
        :return:
        """
        order_detail = self.pay_api.order_pay_detail(order_no)
        need_pay_amount = self.order_need_pay_amount(order_no)
        order_pay_list = get_json_result(order_detail, '$..payApiResponseList')
        if need_pay_amount > 0.0:
            if order_pay_list is not []:
                self.check_order_pay_mode(order_pay_list)
                pay_amount = self.order_need_pay_amount(order_no)
                return pay_amount
            return need_pay_amount
        elif need_pay_amount < 0.0:
            for i in order_pay_list:
                pay_no = i['payNo']
                refund_amount = i['canRefundAmount']
                self.pay_api.pay_common_refund(order_no, refund_amount, pay_no)
            pay_amount = self.order_need_pay_amount(order_no)
            return pay_amount
        else:
            return need_pay_amount

    def order_pay(self, order_no: Text) -> BaseResponseDto:
        """
        订单支付
        :param order_no: 订单编码
        :return:
        """
        try:
            self.user_api.check_user_is_work()
            pay_amount = self.order_pay_amount_handle(order_no)
            if pay_amount > 0.0:
                pay_mode_id = self.pay_api.get_pay_mode_id()
                self.pay_api.cash_pay(order_no, pay_amount, pay_mode_id)
            self.pay_api.confirm_checkout(order_no)
            result_info = BaseResponseDto(data="订单[{}]结账成功~".format(order_no))
            return result_info
        except RequestFailedException as e:
            result_info = BaseResponseDto(code="5000", message="请求失败!", data="{}".format(e))
            return result_info

    def all_order_pay(self) -> BaseResponseDto:
        """按照品牌批量结账"""
        table_list_response = self.table_api.table_list('5')
        table_order_list = get_json_result(table_list_response, "$.data..orderNo")
        if type(table_order_list) is list:
            pay_result = []
            for i in table_order_list:
                order_pay_result = self.order_pay(i)
                pay_result.append(order_pay_result)
            result_info = BaseResponseDto(data=pay_result)
            return result_info
        elif type(table_order_list) is str:
            result_info = self.order_pay(table_order_list)
            return result_info
        else:
            result_info = BaseResponseDto(data="当前品牌没有可结账订单,请检查请求参数后重试~")
            return result_info


if __name__ == '__main__':
    test = OrderPayServer("823882", "sit")
    print(test.all_order_pay())
